package cn.hfjava.kz.controller;

import cn.dev33.satoken.util.SaResult;
import cn.hfjava.kz.entity.dto.DocumentQueryDto;
import cn.hfjava.kz.entity.dto.DocumentUpdateDto;
import cn.hfjava.kz.entity.po.Document;
import cn.hfjava.kz.entity.vo.DocumentQueryVo;
import cn.hfjava.kz.entity.vo.PageVO;
import cn.hfjava.kz.service.DocumentService;
import cn.hutool.core.bean.BeanUtil;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.tags.Tag;
import jakarta.annotation.Resource;
import org.springframework.web.bind.annotation.*;

import java.util.List;
import java.util.Objects;

@RestController
@RequestMapping("/api/v1/document")
@Tag(name = "文档管理模块")
public class DocumentController {
    @Resource
    DocumentService documentService;

    /**
     * 按组合（标题、类型、下载状态）条件分页查询文档信息列表
     * @param documentQueryDto
     * @return
     */
    @Operation(summary = "分页查询文档信息", description = "按组合（标题、类型、下载状态）条件分页查询文档信息列表")
    @PostMapping("/listDocument")
    public SaResult listDocument(@RequestBody DocumentQueryDto documentQueryDto) {
        PageVO<List<DocumentQueryVo>> listPageVO = documentService.documentVoList(documentQueryDto);
        return SaResult.ok("文档信息查询成功!").setData(listPageVO);
    }


    /**
     * 修改文档相关信息
     * @return
     */
    @Operation(summary = "修改文档信息", description = "修改文档相关信息")
    @PostMapping("/updateDoc")
    public SaResult updateDoc(@RequestBody DocumentUpdateDto documentUpdateDto) {
        Integer docId = documentUpdateDto.getId();
        Document doc = documentService.getById(docId);
        if (doc == null) {
            return SaResult.error("此文档不存在");
        }
        if (doc.getDeleted() == 1) {
            return SaResult.error("此文档已被删除");
        }
        Document targetDoc = new Document();
        BeanUtil.copyProperties(documentUpdateDto, targetDoc, true);
        documentService.updateById(targetDoc);
        return SaResult.ok("文档更新成功！");
    }


    /**
     * 逻辑删除文档
     */
    @Operation(summary = "逻辑删除文档", description = "逻辑删除文档")
    @GetMapping("/deleteDoc")
    public SaResult deleteDoc(@RequestParam Integer docId) {
        if (documentService.getById(docId).getDeleted().equals(1)){
            return SaResult.error("此文档已被删除");
        }
        List<Integer> docIds = documentService.searchIds();
        for (Integer id : docIds) {
            if (Objects.equals(id, docId)){
                documentService.getById(docId).setDeleted(1);
                return SaResult.ok("文档删除成功！");
            }
        }
        return SaResult.error("此文档不存在");
    }
}
